import axios from "axios";
// 进度条插件
// import progress from "./progress";
// import { toast } from "vue-sonner";
import { useRouter } from "vue-router";
import { storeVuex } from "@/store/modules/user";
import {ElMessage} from "element-plus";
import {storeToRefs} from "pinia";
import router from "@/router";
// 接口缓存插件
// import { buildWebStorage, setupCache } from "axios-cache-interceptor";

//暂时不用
const instance = axios.create({
	baseURL: "http://127.0.0.1:3000/Admin/",
	timeout: 10000,
	headers: {
		Accept: "application/json, text/plain, */*",
		"Content-Type": "application/json",
		"X-Requested-With": "XMLHttpRequest",
	},
});

//接口请求头
//axios.defaults.baseURL = import.meta.env.BaseUrl_Api+"/Admin/";
//axios.defaults.baseURL = "http://113.45.207.53:3001/";


axios.defaults.baseURL = "http://127.0.0.1:3001/";


axios.interceptors.request.use((config:any) => {
	//进度条
	//progress.start();
	const {accessToken} = storeVuex()
	if (accessToken) {
		config.headers['Authorization'] = `Bearer ${accessToken}`; // 添加 Authorization 头
	}
	else{
		if(router.currentRoute.value.fullPath!='/login'){
			ElMessage.error('登录信息失效');
		}
	}
	return config;
});

axios.interceptors.response.use(
	(response:any) => {
		//progress.close();
		const data = response.data;
		console.log('请求结果',data)
		// // 判断是否成功
		// if (data.status == 1) {
		// 	ElMessage.success(data.msg)
		// }else{
		// 	ElMessage.error(data.msg)
		// }
		return response;
		// }
		// //storage.remove(response.id);
		// //toast.error(data.msg || "出现未知错误");
		// return Promise.reject(new Error());
	},
	(error:any) => {
		const status = error.response?.status;
		console.log(123123,status)
		switch (status) {
		case 401:
				//token过期 取消登录
				storeVuex().logout();
				ElMessage.error(error.message)
				break;
			case 403:
				error.message = "拒绝访问";
				break;
			case 404:
				error.message = "请求地址出错";
				break;
			case 405:
				useRouter().push({ name: "renew" });
				break;
			case 408:
				error.message = "请求超时";
				break;
			case 500:
				error.message = "服务器内部错误";
				break;
			case 501:
				error.message = "服务未实现";
				ElMessage({
					message: error.response.data.msg,
					type: 'error'
				})
				break;
			case 502:
				error.message = "网关错误";
				break;
			case 503:
				error.message = "服务不可用";
				break;
			case 504:
				error.message = "网关超时";
				break;
			case 505:
				error.message = "HTTP 版本不受支持";
				break;
			default:
				error.message = "出现未知错误";
				ElMessage.error("出现未知错误")
				// storeVuex().logout();
				break;
		}
		// toast.error(error.message);
		return Promise.reject(error);
	}
);
export default axios;
